﻿using System;
using System.IO;
using UnityEngine;
using System.Collections.Generic;
using UnityEditor.SceneManagement;
using UnityEngine.SceneManagement;

namespace winS.UnityEditor
{
    /// <summary>
    /// Provides Scene utility for Editor.
    /// </summary>
    public static class EditorSceneUtility
    {
        /// <summary>
        /// 获取当前激活的 <see cref="Scene"/>
        /// </summary>
        public static Scene currentScene => SceneManager.GetActiveScene();

        /// <summary>
        /// 场景是否存在
        /// </summary>
        /// <param name="pathRelativeProject">基于项目文件夹的场景文件路径</param>
        public static bool Exist(string pathRelativeProject)
        {
            string assetsDirectoryPath = Application.dataPath;
            assetsDirectoryPath = assetsDirectoryPath.Remove(assetsDirectoryPath.Length - 6, 6);
            return File.Exists($"{assetsDirectoryPath}/{pathRelativeProject}");
        }
        /// <summary>
        /// 复制一个场景到一个新的场景.
        /// 场景中的所有对象都会被拷贝到新场景中并隐藏
        /// </summary>
        /// <param name="pathRelativeProject">要拷贝场景文件的路径, 基于项目文件夹</param>
        public static Scene CopyScene(string pathRelativeProject)
        {
            return CopyScene(pathRelativeProject, null);
        }
        /// <summary>
        /// 复制一个场景到一个新的场景.
        /// 场景中的所有对象都会被拷贝到新场景中并隐藏
        /// </summary>
        /// <param name="pathRelativeProject">要拷贝场景文件的路径, 基于项目文件夹</param>
        /// <param name="completedCallback">当复制完成时的回调</param>
        public static Scene CopyScene(string pathRelativeProject, Action completedCallback)
        {
            Scene scene = EditorSceneManager.OpenScene(pathRelativeProject);
            List<GameObject> rootGameObjects = new List<GameObject>();
            scene.GetRootGameObjects(rootGameObjects);
            Scene newScene = EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Additive);
            SceneManager.SetActiveScene(newScene);
            Transform environment = new GameObject("Root").transform;
            environment.gameObject.hideFlags = HideFlags.HideInHierarchy;
            foreach (var gameObject in rootGameObjects) UnityEngine.Object.Instantiate(gameObject, environment);
            SceneManager.UnloadSceneAsync(scene).completed += _ => completedCallback?.Invoke();
            return newScene;
        }
        /// <summary>
        /// 打开场景
        /// </summary>
        public static Scene OpenScene(string pathRelativeProject)
        {
            return EditorSceneManager.OpenScene(pathRelativeProject);
        }
        /// <summary>
        /// Create a new scene.
        /// </summary>
        public static Scene CreateScene(string sceneName)
        {
            Scene scene = EditorSceneManager.NewScene(NewSceneSetup.EmptyScene);
            scene.name = sceneName;
            return scene;
        }
    }
}